<script setup>
import {nextTick, onMounted, onUnmounted, ref} from "vue";
import axios from "axios";
import {convertDevices, convertStatistics, getChartType} from "@/util.js";
import EZUIKit from 'ezuikit-js';
import * as echarts from "echarts";

const UIKitDEMO = ref(null);
const cameraToken = ref(null);
const deviceTableHead = ref(["序号", "设备编号", "设备名称", "设备类型", "操作"]);
const greenhouseInfo = ref([["编号", "0454"], ["面积", "5.14亩"], ["地址", "基地"], ["设备", "?台"]]);
const devices = ref([{}]);
const statistics = ref([])
const highlight = ref(0);
const showPhoto = ref(false);
const photoIndex = ref(0);
const showDialog = ref(false)
const unBindDevices = ref([])
const greenhouseId = ref()

function reSizeCamera(w, h) {
  if (UIKitDEMO.value !== null) {
    UIKitDEMO.value.reSize(w, h);
  }
}

function getData() {
  axios({
    method: 'get',
    url: '/api/greenhouse/getGreenhouse',
    headers: {
      'user_token': localStorage.getItem('user_token')
    }
  }).then(res => {
    const greenhouse = res.data;
    greenhouseId.value = greenhouse.id;
    console.log(greenhouse)

    axios({
      method: 'get',
      url: '/api/greenhouse/getUnbindDevices',
      headers: {
        'user_token': localStorage.getItem('user_token')
      }
    }).then(res => {
      unBindDevices.value = res.data
    })

    greenhouseInfo.value[0][1] = greenhouse["greenhouseName"];
    greenhouseInfo.value[1][1] = greenhouse["greenhouseArea"];
    greenhouseInfo.value[2][1] = greenhouse["greenhouseLocation"];
    greenhouseInfo.value[3][1] = greenhouse["devices"].length + "台";
    cameraToken.value = greenhouse['cameraToken'];
    devices.value = convertDevices(greenhouse["devices"]);
    statistics.value = convertStatistics(greenhouse["devices"]);
    console.log(statistics.value);
    for (let i = 0; i < devices.value.length; i++) {
      const device = devices.value[i];
      if (device['deviceAddress'] && device['deviceAddress'] !== null) {
        UIKitDEMO.value = new EZUIKit.EZUIKitPlayer({
          id: `ezuikit-player`,
          url: device['deviceAddress'],
          accessToken: cameraToken.value
        });
        updateHighLight(highlight.value);
        break;
      }
    }
  }).catch(err => {
    console.log(err);
  });
}

function addDevice(deviceId, greenHouseId) {
  axios({
    method: 'get',
    url: '/api/greenhouse/addDevice?device=' + deviceId + '&greenhouse=' + greenHouseId,
    headers: {
      'user_token': localStorage.getItem('user_token')
    }
  }).then(res => {
    if (res.data.msg === 'ok') {
      showDialog.value = false;
      getData()
    } else {
      alert(res.data.msg)
    }

  })

}

function openAddDevice() {
  showDialog.value = true;
}

function updateHighLight(h) {
  showPhoto.value = false;
  highlight.value = h;
  if (devices.value[highlight.value]['deviceAddress'] === null) {
    reSizeCamera(0, 0);
    initChart();
  } else {
    reSizeCamera(720, 480);
  }
}

function togglePhoto() {
  showPhoto.value = !showPhoto.value;
  if (showPhoto.value) {
    reSizeCamera(0, 0);
  } else {
    reSizeCamera(720, 480);
  }
}

function changePhotoIndex(count) {
  photoIndex.value += count;
  if (photoIndex.value < 0) {
    photoIndex.value = statistics.value[highlight.value].length - 1;
  } else if (photoIndex.value >= statistics.value[highlight.value].length) {
    photoIndex.value = 0;
  }
}

const chartRef = ref(null);
let chartInstance = null;
const initChart = () => {
  nextTick(() => {
    if (chartInstance) chartInstance.dispose();
    chartInstance = echarts.init(chartRef.value);
    const device = devices.value[highlight.value];
    const statistic = statistics.value[highlight.value];
    const data = [];
    for (let i = 0; i < statistic.length; ++i) {
      data.push(statistic[i]['statisticValue']);
    }
    const x = [];
    for (let i = 0; i < statistic.length; ++i) {
      x.push(statistic[i]['time']);
    }
    const option = {
      title: {
        text: device["deviceName"]
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: x
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: data,
        type: getChartType(device["deviceName"])
      }]
    };
    chartInstance.setOption(option);
  });
};
onMounted(() => {
  getData();
});
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});
setInterval(() => {
  getData();
}, 1000 * 60 * 3);
</script>

<template>
  <div class="gh-out-div">

    <div class="dialog-box" v-if="showDialog">
      <div class="gh-dialog-top">
        <p class="gh-dialog-title">添加设备</p>
        <div class="gh-button gh-dialog-close-button" @click="showDialog = false"><p>关闭</p></div>
      </div>
      <table style="color: #181818" border="1">
        <thead>
        <tr>
          <th v-for="head in deviceTableHead">{{ head }}</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(unbindDevice,index) in unBindDevices">
          <td>{{ index + 1 }}</td>
          <td>{{ unbindDevice.deviceNumber }}</td>
          <td>{{ unbindDevice.deviceName }}</td>
          <td>{{ unbindDevice.deviceType }}</td>
          <td>
            <div class="gh-button gh-dialog-add-button" @click="addDevice(unbindDevice.id,greenhouseId)"><p>添加</p>
            </div>
          </td>
        </tr>
        </tbody>

      </table>


    </div>

    <div class="gh-info-out-div">
      <div class="gh-info-gh-info-out-div">
        <div class="gh-info-info-div" v-for="greenhouse in greenhouseInfo">
          <p>{{ greenhouse[0] }}</p>
          <p>{{ greenhouse[1] }}</p>
        </div>
      </div>
      <div class="gh-info-device-info-out-div">
        <div class="gh-info-device-div" v-for="(device, index) in devices"
             :class="{'gh-info-device-div-active': highlight === index}" @click="updateHighLight(index)">
          <p>{{ device["deviceName"] }}</p>
          <p>{{ device["statisticValue"] }}</p>
          <p>{{ device["deviceUnit"] }}</p>
        </div>

        <div class="gh-info-device-div" @click="openAddDevice()"
             style="position: relative;font-size: 60px;color: #181818;cursor: pointer">
          <div style="position: absolute;top:0">+</div>
        </div>
      </div>
    </div>
    <div class="gh-detail-out-div">
      <div class="gh-detail-div">
        <div ref="chartRef" style="width: 720px; height: 480px;" v-show="devices[highlight]['deviceAddress'] === null"/>
        <div id="ezuikit-player"/>
        <div class="gh-detail-photo-div" v-if="!(devices[highlight]['deviceAddress'] === null) && showPhoto">
          <div class="gh-detail-photo-info-div">
            <div class="gh-button gh-detail-photo-switch-button" @click="changePhotoIndex(-1)"><p>上一个</p></div>
            <p class="gh-detail-photo-info-p">{{ statistics[highlight][photoIndex]['time'] }}</p>
            <div class="gh-button gh-detail-photo-switch-button" @click="changePhotoIndex(1)"><p>下一个</p></div>
          </div>
          <img :src="'data:image/jpg;base64,' + statistics[highlight][photoIndex]['statisticPhoto']" width="600px"
               height="400px"
               alt="The Image has expired"/>
        </div>
      </div>
      <div class="gh-detail-device-info-out-div">
        <div class="gh-detail-device-info-div">
          <p>设备编号:</p>
          <p>{{ devices[highlight]['deviceNumber'] }}</p>
        </div>
        <div class="gh-detail-device-info-div">
          <p>设备类型:</p>
          <p>{{ devices[highlight]['deviceType'] }}</p>
        </div>
        <div class="gh-detail-device-info-div">
          <p>设备名称:</p>
          <p>{{ devices[highlight]['deviceName'] }}</p>
        </div>
        <div class="gh-detail-device-info-div" v-show="!(devices[highlight]['deviceAddress'] === null)">
          <div class="gh-button gh-detail-photo-button" @click="togglePhoto()">
            <p>历史图片</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.gh-info-gh-info-out-div, .gh-out-div, .gh-detail-out-div, .gh-detail-photo-info-div {
  display: flex;
  flex-direction: row;
}

.gh-info-info-div, .gh-info-out-div, .gh-detail-device-info-out-div, .gh-detail-device-info-div, .gh-detail-photo-div {
  display: flex;
  flex-direction: column;
}

p {
  color: black;
}

.gh-info-gh-info-out-div {
  width: 100%;
  height: 12%;
}

.gh-info-out-div {
  border-radius: 10px;
  border-color: #e6e6e6;
  background: white;
  width: 480px;
  height: 600px;
}

.gh-detail-out-div {
  border-radius: 10px;
  border-color: #e6e6e6;
  background: white;
  width: 1000px;
  height: 600px;
  margin-left: 20px;
}

.gh-info-info-div {
  border-bottom: 1px solid #e6e6e6;
  border-right: 1px solid #e6e6e6;
  width: 25%;
  justify-content: center;
  align-items: center;
}

.gh-info-info-div:last-child {
  border-top-right-radius: 10px;
}

.gh-detail-device-info-div {
  border-bottom: 1px solid #e6e6e6;
  width: 100%;
  height: 80px;
  justify-content: center;
  align-items: center;
}

.gh-detail-device-info-out-div {
  border-left: 1px solid #e6e6e6;
  width: 25%;
}

.gh-info-device-info-out-div {
  width: 110%;
  height: 88%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  overflow: auto;
}

.gh-info-device-div {
  width: 120px;
  height: 120px;
  margin: 20px 20px;
  border-radius: 10px;
  border-color: #e6e6e6;
  background: #dddddd;
  outline-color: #282828;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.gh-info-device-div p {
  color: black;
  font-weight: bold;
}

.gh-info-device-div p:nth-child(2) {
  font-size: 20px;
}

.gh-info-device-div-active {
  background: #d2d525;
}

.gh-detail-div {
  width: 75%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.gh-detail-photo-switch-button {
  width: 100px;
  height: 25px;
}

.gh-detail-photo-button {
  width: 200px;
  height: 50px;
}

.gh-button {
  background: #189dc6;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  cursor: pointer;
}

.gh-button:hover {
  background: #41bedd;
}

.gh-button p {
  color: white;
  font-weight: bold;
  cursor: pointer;
}

.gh-detail-photo-div {
  justify-content: center;
  align-items: center;
}

.gh-detail-photo-info-div {
  margin: 20px 20px;
}

.gh-detail-photo-info-p {
  margin: 0 10px;
}

.dialog-box {
  z-index: 999999;
  position: absolute;
  background-color: #dddddd;
  width: 32vw;
  height: 75vh;
  left: 35vw;
  border-radius: 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

.gh-dialog-top {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  width: 80%;
}

.gh-dialog-close-button {
  width: 120px;
  height: 30px;
}

.gh-dialog-add-button {
  width: 40px;
  height: 20px;
}

.gh-dialog-title {
  color: #181818;
  font-weight: bold;
  font-size: 25px;
}
</style>